<template>
  <el-form-item :label="label" v-if="isShow">
    <component v-if="cProps.isComponent" :is="cProps.component" v-model="model" v-bind="cProps.props" :disabled="isDisabled"
               @change="change" @input="input"/>
    <template v-else>
      <el-select v-if="cProps.component === 'select'" v-model="model" v-bind="cProps.props" :disabled="isDisabled"
                 @change="change" @input="input">
        <el-option
            v-for="option in cProps.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
        />
      </el-select>
    </template>
  </el-form-item>
  <div v-else/>
</template>

<script setup>
import {ElInput, ElInputNumber, ElTreeSelect, ElSwitch, ElTimeSelect, ElTimePicker, ElDatePicker, ElFormItem, ElSelect, ElOption} from "element-plus"
import {computed, defineEmits, defineModel, defineProps} from "vue";
const components = {
  input: ElInput,
  inputNumber: ElInputNumber,
  treeSelect: ElTreeSelect,
  switch: ElSwitch,
  timeSelect: ElTimeSelect,
  timePicker: ElTimePicker,
  datePicker: ElDatePicker,
}
const _props = defineProps({
  isShow: {
    type: Boolean,
    default: true,
  },
  isComponent: Boolean,
  component: String,
  label: String,
  props: Object,
  options: Array,
  action: String,
})
const cProps = computed(() => {
  const result = {..._props}
  const isDate = _props.component === 'datePicker'
  if (!_props.props) {
    result.props = {placeholder: `请输入${_props.label}`}
    if (isDate) {
      result.props.format = 'YYYY-MM-DD'
      result.props.valueFormat = 'YYYY-MM-DD'
    }
  } else {
    if (isDate) {
      if (!_props.props.format) {
        result.props.format = 'YYYY-MM-DD'
      }
      if (!_props.props.valueFormat) {
        result.props.valueFormat = 'YYYY-MM-DD'
      }
    }
    if (!_props.props.placeholder) {
      result.props.placeholder = `请输入${_props.label}`
    }
  }
  const component = components[_props.component || 'input']
  result.component = component || _props.component
  result.isComponent = !!component
  return result
})
const model = defineModel()

const isDisabled = computed(() => {
  if (cProps.value.props && cProps.value.props.disabled !== undefined) {
    return cProps.value.props.disabled
  }
  return _props.action === 'detail'
})

const emit = defineEmits(['change', 'input'])

function change(value) {
  emit('change', value)
}
function input(value) {
  emit('input', value)
}
</script>
